package cn.graydove.bot.service.impl;

import cn.graydove.bot.enums.Boss;
import cn.graydove.bot.model.entity.QqGroup;
import cn.graydove.bot.model.entity.User;
import cn.graydove.bot.repository.GroupRepository;
import cn.graydove.bot.repository.UserRepository;
import cn.graydove.bot.service.BossManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BossManagerImpl implements BossManager {
    private static final Boss[] bosses = Boss.values();

    private UserRepository userRepository;

    private GroupRepository groupRepository;

    public BossManagerImpl(UserRepository userRepository, GroupRepository groupRepository) {
        this.userRepository = userRepository;
        this.groupRepository = groupRepository;
    }

    private void next(QqGroup group) {
        int num = bosses.length;
        group.setBaseLine(0);
        group.setRound(group.getRound() + (group.getNow() + 1) / num);
        group.setNow((group.getNow() + 1) % num);
        group.setCurrentHealth(bosses[group.getNow()].getHp());

        groupRepository.save(group);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public QqGroup attack(QqGroup group, User attacker, int damage) {
        return attack(group, attacker, damage, false);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class})
    public QqGroup attack(QqGroup group, User attacker, int damage, boolean isCompensate) {
        attacker.setDamage(attacker.getDamage() + damage);
        if (!isCompensate)
            attacker.setAttack(attacker.getAttack() + 1);
        userRepository.save(attacker);

        group.setCurrentHealth(group.getCurrentHealth() - damage);
        if (group.getCurrentHealth() <= 0) {
            for (var u : group.getUsers()) {
                if (u.getOnTree()) {
                    u.setOnTree(false);
                    userRepository.save(u);
                }
            }
            next(group);
        }
        return groupRepository.save(group);
    }

    @Override
    public void reset(QqGroup group, int r, int n, int hp) {
        group.setRound(r);
        group.setNow(n);
        group.setCurrentHealth(hp);
        group.setBaseLine(0);
        groupRepository.save(group);
    }

    @Override
    public String getCurrentBoss(QqGroup group) {
        return getBoss(group.getNow());
    }

    @Override
    public String getBoss(int order) {
        return bosses[order].getName();
    }

    @Override
    public String getMessage(QqGroup group) {
        return "当前" + group.getRound() + "周目，" + getCurrentBoss(group) + "剩余" + group.getCurrentHealth() + "生命。";
    }
}
